package diversion.v1.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;


/**
 *  Description of the Class
 *
 * @author    jmricker
 */
class doComms implements Runnable {
    private Server parent;
    private Socket socket;
    private Dispatcher dispatch;

    /**
     *  Constructor for the doComms object
     *
     * @param  parent  Description of the Parameter
     * @param  socket  Description of the Parameter
     */
    doComms(Socket socket, Dispatcher dispatch) {
        this.socket = socket;
        this.dispatch = dispatch;
    }

    /**
     *  Main processing method for the doComms object
     */
    public void run() {
        try {

            // Get input from the socket
            BufferedReader instream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintStream    outstream = new PrintStream(socket.getOutputStream());
            KXmlParser     parser = new KXmlParser();
            ArrayList      commandList = new ArrayList();
            int            eventType = parser.getEventType();
            int            depth = 0;

            parser.setInput(instream);
            do  {
                if (eventType == parser.START_TAG) {
                    depth++;

                    String name = parser.getName().toLowerCase();

                    commandList.add("<" + name);

                    for (int i = 0; i < parser.getAttributeCount(); i++) {
                        commandList.add(":" + parser.getAttributeName(i));
                        commandList.add("=" + parser.getAttributeValue(i));
                    }

                }  else if (eventType == parser.TEXT) {

                        commandList.add('"' + parser.getText());
                        
                    } else if (eventType == parser.END_TAG) {
                        depth--;
                        
                        if (depth == 0) {
                            outstream.print( dispatch.proccessCommand(socket, commandList) );
                            commandList.clear();
                        }
                    }

                eventType = parser.next();
            } while ((eventType != parser.END_DOCUMENT) && socket.isConnected());

        }  catch (IOException ioe) {
            System.out.println("IOException on socket listen: " + ioe);
            ioe.printStackTrace();
        }  catch (XmlPullParserException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException ex) {}
            System.out.println("Socket closed. " + socket);
        }
    }
}